package com.software.project_view.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.software.project_view.entity.Block;
import com.software.project_view.entity.SubmitItem;
import com.software.project_view.mapper.BlockMapper;
import com.software.project_view.mapper.SubmitItemMapper;
import com.software.project_view.service.SubmitItemService;
import com.software.project_view.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class SubmitItemServiceImpl extends ServiceImpl<SubmitItemMapper, SubmitItem> implements SubmitItemService {


    @Autowired
    private BlockMapper blockMapper;

    private static final Integer DIFFICULTY = 5;

    public R submit(SubmitItem submitItem) {
        submitItem.setSubmitTime(SubmitItem.formatTime(new Date()));
        submitItem.setId(UUID.randomUUID().toString().replace("-",""));
        Block block = new Block(JSON.toJSONString(submitItem), blockMapper.selectRecent().getHash());
        block.mineBlock(DIFFICULTY);
        int insert = blockMapper.insert(block);
        if (insert > 0) {
            return R.success().message("提交成功");
        } else {
            return R.error().message("提交失败");
        }
    }
}
